import React, { useEffect, useRef, useState, forwardRef, useImperativeHandle } from 'react';
import Vditor from 'vditor';
import "vditor/dist/index.css";
import styles from './vditor.less';;
import request from '@/utils/request';
import { upload } from '@/services/vditor';
import iconImg from '@/assets/knowledgeFile/2.svg';
import { formatMessage } from 'umi-plugin-react/locale';
var vditor = null, vditorNew = 0;

function MarkdownEditor(props, ref) {
    useImperativeHandle(ref, () => ({
        setContent: setEditorContentAsync,
    }))
    const editorRef = useRef(null);
    const [vditorCurrent, setVditorCurrent] = useState({})
    useEffect(() => {
        var vditor = new Vditor(editorRef.current, {
            value: props.value,
            cache: false,
            input: (value) => props.onChange(value),
            // cache: { id: 'vditor' },
            height: props.height,
            cdn: staticPath + '/vditor',
            counter: { enable: true },
            toolbar: [
                { name: 'emoji', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.emoji', defaultMessage: '表情' }) },
                { name: 'headings', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.headings', defaultMessage: '标题' }) },
                { name: 'bold', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.bold', defaultMessage: '粗体' }) },
                { name: 'italic', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.italic', defaultMessage: '斜体' }) },
                { name: 'strike', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.strike', defaultMessage: '删除线' }) },
                { name: 'link', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.link', defaultMessage: '链接' }) },
                '|',
                { name: 'list', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.list', defaultMessage: '无序列表' }) },
                { name: 'ordered-list', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.ordered-list', defaultMessage: '有序列表' }) },
                { name: 'check', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.check', defaultMessage: '任务列表' }) },
                { name: 'outdent', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.outdent', defaultMessage: '列表反向缩进' }) },
                { name: 'indent', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.indent', defaultMessage: '列表缩进' }) },
                '|',
                { name: 'quote', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.quote', defaultMessage: '引用' }) },
                { name: 'line', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.line', defaultMessage: '分隔线' }) },
                { name: 'code', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.code', defaultMessage: '代码块' }) },
                { name: 'inline-code', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.inline-code', defaultMessage: '行内代码' }) },
                { name: 'insert-before', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.insert-before', defaultMessage: '起始插入行' }) },
                { name: 'insert-after', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.insert-after', defaultMessage: '末尾插入行' }) },
                '|',
                { name: 'upload', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.upload', defaultMessage: '上传图片或文件' }) },
                // { name: 'record', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.record', defaultMessage: '录音' }) },
                { name: 'table', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.table', defaultMessage: '表格' }) },
                '|',
                { name: 'undo', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.undo', defaultMessage: '撤销' }) },
                { name: 'redo', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.redo', defaultMessage: '重做' }) },
                '|',
                { name: 'fullscreen', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.fullscreen', defaultMessage: '全屏切换' }) },
                { name: 'edit-mode', tip: formatMessage({ id: 'platformManagement.agreementInfo.toolbar.edit-mode', defaultMessage: '切换编辑模式' }), icon: `<img style="height: 16px" src="${iconImg}" />` },
                // 'both', 'preview', 'outline', 'code-theme', 'content-theme', 'export', 'devtools', 'info', 'help', 'br'
            ],
            placeholder: formatMessage({ id: 'platformManagement.agreementInfo.editorTip'}),
            preview: {
                show: false,
                actions: [],
            },
            after: () => {
                vditorNew = 1;
                props.setContent();
            },
            upload: {
                // accept: 'image/jpeg,image/png,image/gif,image/jpg,image/bmp', // 图片格式
                // max: 2 * 1024 * 1024,  // 控制大小
                multiple: true, // 是否允许批量上传
                fieldName: 'file', // 上传字段名称
                url: '/cloud/file/upload',
                success: function (textarea, msg) {//textarea  
                    //将返回的信息传为json对象 
                    let msgData = JSON.parse(msg)
                    if (msgData?.state === "SUCCESS") {//请求成功  
                        vditorCurrent[props.id].tip('上传成功', 1500);
                        let content;
                        //获取文件后缀，判断类型  
                        let temp = msgData.original.substring(msgData.original.lastIndexOf('.') + 1)
                        if (temp == "png" || temp == "jpg") {
                            content = "![" + msgData.original + "](" + msgData.url + ")"
                        } else {
                            content = "[" + msgData.original + "](" + msgData.url + ")"
                        };
                        //插入上传文件后的markdown代码  
                        vditorCurrent[props.id].insertValue(content)
                    }
                }
            },
        });
        vditorCurrent[props.id] = vditor;
        setVditorCurrent(vditorCurrent)
        if (props.setVditorRef) {
            props.setVditorRef(vditor)
        };
        return () => {
            vditorNew = 0;
            vditor = null;
        };
    }, [])

    const setEditorContentAsync = (value, callback) => {
        // try {
        if (vditorCurrent[props.id] && vditorCurrent[props.id].setValue && vditorNew == 1) {
            vditorCurrent[props.id].setValue(value);
        } else if (callback) {
            callback()
        }
        // } catch (error) {
        //     console.log(error);
        // }
    };

    return (
        <div className={styles["markdown-editor"]} id={props.id} ref={editorRef}></div>
    )
}

export default React.forwardRef(MarkdownEditor);
